import { schema, kernel, model } from '@/ts/base'
import { AddNodeType } from '@/utils/work'
import { ITarget } from '@/ts/core/target/base/target'
import { TargetType } from '@/ts/core/public/enums'
import { ICompany, IDepartment } from '@/ts/core'
import { IGroup } from '@/ts/core/target/outTeam/group'
import { ICohort } from '@/ts/core/target/outTeam/cohort'

class Work {
  async findWorkEntityAsync(id: string): Promise<schema.XEntity | undefined> {
    const res = await kernel.queryEntityById({ id: id })
    if (res.success && res.data?.id) {
      return res.data
    }
  }
  buildTree(data: any[]) {
    const tree: any[] = []
    const map: any = {}

    // 将所有节点添加到一个映射中，以便快速查找
    data.forEach(item => {
      map[item.id] = { ...item, children: [] }
    })
    data.forEach(item => {
      if (item.parentId === undefined) {
        tree.push(map[item.id])
      } else if (map[item.parentId]) {
        map[item.parentId].children.push(map[item.id])
      }
    })
    Object.keys(map).forEach(key => {
      if (map[key].children.length === 0) {
        map[key].children = undefined
      }
    })

    return tree
  }

  // 编译内部机构
  _deepDepartments = (
    departments: IDepartment[],
    parentId?: string
  ): model.FiledLookup[] => {
    const result: any[] = []
    for (const department of departments) {
      if (department.children && department.children.length > 0) {
        result.push(
          ...this._deepDepartments(department.children, department.id)
        )
      }

      result.push({
        id: department.metadata.id,
        text: `${department.metadata.name}(${department.metadata.code})`,
        parentId: parentId,
        value: department.metadata.id,
        disabled: false,
        expanded: true,
        checkable: false
      })
    }
    return result
  }

  /** 加载组织身份树 */
  _deepTreeItems = (
    node: schema.XWorkNode,
    targets: ITarget[],
    isChildren?: boolean,
    pid?: string
  ): model.FiledLookup[] => {
    const result: any[] = []
    for (const item of targets) {
      if (item.id === node.destId || isChildren) {
        isChildren = true
        //插入节点
        result.push({
          id: item.id,
          text: item.name,
          parentId: item.id === node.destId ? undefined : pid,
          value: item.id,
          disabled: true, //禁用选择
          expanded: true //打开子集
        })
        //插入节点下的身份
        if (item.identitys.length > 0) {
          result.push(
            ...item.identitys.map(v => ({
              id: v.id,
              text: `${v.name}(身份)`,
              parentId: item.id,
              value: v.id
            }))
          )
        }
      }
      if (item.subTarget) {
        result.push(
          ...this._deepTreeItems(node, item.subTarget, isChildren, item.id)
        )
      }
    }
    return result
  }

  // 递归加载部门及子部门下的角色、人员等
  async loadDepartments(departments: IDepartment[]) {
    for (const department of departments) {
      await department.loadIdentitys()
      await department.loadChildren()
      await department.loadMembers()
      if (department.children && department.children.length > 0) {
        await this.loadDepartments(department.children)
      }
    }
  }

  // 递归加载组织群下的角色、人员等
  async loadGroups(groups: IGroup[]) {
    for (const group of groups) {
      await group.loadIdentitys()
      await group.loadChildren()
      await group.loadMembers()
      if (group.children && group.children.length > 0) {
        await this.loadGroups(group.children)
      }
    }
  }

  // 递归加载群组下的角色、人员等
  async loadCohorts(cohorts: ICohort[]) {
    for (const cohort of cohorts) {
      await cohort.loadIdentitys()
      await cohort.loadMembers()
    }
  }

  // 加载当前被审批办事的单位、人员、部门、群组信息
  async loadContent(target: ITarget | ICompany) {
    await target.loadMembers()
    await target.loadIdentitys()
    const departments = await (target as ICompany).loadDepartments()
    await this.loadDepartments(departments)
    const groups = await (target as ICompany).loadGroups()
    await this.loadGroups(groups)
    await this.loadCohorts((target as ICompany).cohorts)
  }

  convertToFields = (
    node: schema.XWorkNode,
    target: ITarget
  ): model.FieldModel => {
    const field: model.FieldModel = {
      id: node.id,
      propId: node.id,
      code: node.code,
      name: node.name + `-${node.destType}`,
      nodeType: node.nodeType,
      valueType: '用户型',
      widget: '人员搜索框',
      remark: ''
    }
    let team = target
    switch (node.nodeType) {
      case AddNodeType.CUSTOM:
        switch (node.destType) {
          case '角色':
            field.valueType = '用户型'
            field.widget = '内部机构选择框'
            field.options = {
              teamId: team.id
            }
            field.lookups = this._deepDepartments(
              (target as ICompany).departments
            )
            field.treeType = 'single'
            break
          case '身份':
            field.valueType = '描述型'
            field.widget = '多选框'
            field.options = {
              teamId: node.destId
            }
            field.lookups = this._deepTreeItems(node, [target])
            field.treeType = 'multiple'
            break
          default:
            if (TargetType.Group === target.typeName) {
              team = target.space
            }
            field.valueType = '用户型'
            field.widget = '多选框'
            field.options = {
              teamId: team.id,
              searchEnabled: true
            }
            field.lookups = target.members.map(menber => ({
              ...menber,
              id: menber.id,
              value: menber.id,
              icon: menber.icon ? JSON.parse(menber.icon).thumbnail : '',
              iconSize: 52,
              customAcatar: menber.icon ? '' : menber.name,
              text: `${menber.name}(${menber.code})`
            })) as any
            if (field.lookups?.length === 1) {
              field.options!.defaultValue = [field.lookups[0].value]
            }
            field.treeType = 'multiple'
            break
        }
        break
      case AddNodeType.GATEWAY:
        field.valueType = '用户型'
        field.widget = '成员选择框'
        field.options = {
          teamId: team.id
        }
        break
      case AddNodeType.Confluence:
        field.valueType = '用户型'
        field.widget = '内部机构选择框'
        field.options = {
          teamId: team.id
        }
        break
      default:
        break
    }
    return field
  }
}

export default new Work()
